package com.qire.antsrouter.card;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

import com.qire.antscore.common.AssertUtils;
import com.qire.antscore.entity.RouteMeta;
import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.MappingCache;
import com.qire.antsrouter.intercept.InterceptRules;
import com.qire.antsrouter.intercept.Interceptor;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;

import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;

import java.util.List;

/**
 * 楼卡(Activity跳卡)
 */
public class FloorCard extends Postcard<Activity> {

    // 新版风格 转场动画
    private Bundle optionsCompat;
    // 老版 转场动画
    private int enterAnim;
    private int exitAnim;
    // 场景返回代码
    private int requestCode = -1;

    protected FloorCard(RouteMeta routeMeta, Handler handler) {
        super(routeMeta, handler);
    }

    /**
     * 转场动画 新版本风格
     * @param compat 转场兼容参数
     * @return 这张房卡
     */
    public FloorCard withOptionsCompat(ActivityOptionsCompat compat) {
        if (null != compat) {
            this.optionsCompat = compat.toBundle();
        }
        return this;
    }

    /**
     * 转场动画
     * @param enterAnim 转场进入时动画资源Rid
     * @param exitAnim 转场退出时动画资源Rid
     * @return 这张房卡
     */
    public FloorCard withTransition(int enterAnim, int exitAnim) {
        this.enterAnim = enterAnim;
        this.exitAnim = exitAnim;
        return this;
    }

    /**
     * 注入数据
     * @param fieldName 注入字段名
     * @param data      注入数据
     * @return 这张房卡
     */
    public FloorCard withData(String fieldName, Object data) {
        dataContainer.put(fieldName, data);
        return this;
    }

    /**
     * 注入
     * @param activity
     */
    @Override
    public <T extends Activity> void inject(T activity) {
        super.inject(activity);
    }

    /**
     * 转到某个Activity，如果Activity已经打开，则跳转到已经打开的，如果Activity未被打开，则导航打开。
     * 跳转不能用于接收返回值得方式打开Activity，因为已存在的Activity无法和现有的关联，如果需要接受返回代码的Activity使用navigation新建
     */
    public void go() {
        Activity activity = ActivityManageHandler.HANDLER.findActivityBy(routeMeta.<Activity>getDestination());
        if(activity == null) {
            navigation();
        } else {
            if(AssertUtils.notEmpty(dataContainer)) {
                inject(activity);
            }
            ActivityManageHandler.HANDLER.finishTo(activity);
        }
    }

    public void navigation(int requestCode) {
        this.requestCode = requestCode;
        navigation();
    }

    @Override
    public FloorCard navigation() {
        onInterceptions();
        return this;
    }

    public final void onNavigation() {
        final Activity activity = ActivityManageHandler.HANDLER.currentActivity();
        final Context currentContext = activity == null ? AntsRouter.ROUTER.application() : activity;
        final Intent intent = new Intent(currentContext, routeMeta.getDestination());
        intent.putExtra(CARD_KEY, cardId);
        int flags = this.flags;
        if (-1 != flags) {
            intent.setFlags(flags);
        } else if (!(currentContext instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        CardBag.put(cardId, this);

        handler.post(() -> {
            //可能需要返回码
            if (requestCode > 0 && currentContext instanceof Activity) {
                ActivityCompat.startActivityForResult((Activity) currentContext, intent, requestCode, optionsCompat);
            } else {
                ActivityCompat.startActivity(currentContext, intent, optionsCompat);
            }

            if ((0 != enterAnim  || 0 != exitAnim) && currentContext instanceof Activity) {
                //老版本
                ((Activity) currentContext).overridePendingTransition(enterAnim, exitAnim);
            }
            //跳转完成
//                if (null != callback) {
//                    callback.onArrival(postcard);
//                }
        });
    }

    private void onInterceptions() {
        List<InterceptRules> interceptorList = MappingCache.findRulesBy(getGroup());
        if(AssertUtils.isEmpty(interceptorList)) {
            onNavigation();
            return ;
        }
        new Interceptor(this, interceptorList).onInterceptions();
    }

    public void onInterrupt(String message) {
        System.out.println("被拦截了：：=========="+message);
    }

}
